package com.elite.groovy.callback;

import com.elite.groovy.util.EliteBean;
import com.elite.groovy.util.Util;
import com.elite.groovy.kh.KHDBConfig;
import com.elite.groovy.kh.KHUtil;
import com.alibaba.fastjson.JSONObject
import com.wisdge.dataservice.Result;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory
import org.springframework.jdbc.core.JdbcTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @projectName: ngsapi_cs
 * @package: cn.com.callback
 * @className: apiWXLogin
 * @author: LiJT
 * @description: 嵌入微信的中间页面调用此接口实现信息验证重定向-微信体系下Step2
 * @date: 2022-12-19 14:03
 * @version: 1.0
 */

public class apiWXCode implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiWXCode.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");

        String getMethod = request.getMethod();
        log.debug("getMethod:" + getMethod);
        if (!getMethod.equals("GET")) {
            log.error("HTTP请求调用类型错误，接口调用失败：" + getMethod);
            return JSONObject.toJSONString(new Result(Result.ERROR, "HTTP请求调用类型错误，接口调用失败：" + getMethod));
        }

        // 获取数据源List<Map<String, Object>>
        JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());

        String DOMAIN = KHDBConfig.getAPIURL(eliteBean, "SYS-OuterDomain");
        DOMAIN = DOMAIN.endsWith("/") ? DOMAIN : DOMAIN + "/";

        //获取所有参数名
        Enumeration e = request.getParameterNames();
        while (e.hasMoreElements()) {
            String parameterName = (String) e.nextElement();
            log.debug(parameterName + ": " + request.getParameter(parameterName));
        }

        String code = request.getParameter("code"); // 微信自动添加
        String state = request.getParameter("state"); // Html添加
        String opsource = request.getParameter("opsource"); // Html添加
        String opdynid = request.getParameter("opdynid"); // *手动-页面ID
        String expand = request.getParameter("expand"); // *手动-拓展信息
        String taskid = request.getParameter("taskid"); // *手动-taskid

        if (KHUtil.isNull(opdynid)) {
            log.warn("打开页面异常:" + opsource + " opdynid:" + opdynid + " expand:" + expand);
            response.sendRedirect(DOMAIN + "ngs/404.html?ErrorTitle=" + URLEncoder.encode("页面异常", "UTF-8") + "&ErrorInfo=" + URLEncoder.encode("错误代码：DynNull 描述:页面ID错误", "UTF-8").replaceAll("\\+", "%20"));
        } else {

            opdynid = KHUtil.isNull(opdynid) ? "D4092I" : opdynid;

            log.debug("回调参数信息【code】：" + code + "【state】：" + state + "【opsource】：" + opsource + "【opdynid】：" + opdynid + "【expand】：" + expand);

            // 调用微信获取OPENID
            String APPID = KHDBConfig.getParamConfig(eliteBean, opsource + "-appID");
            String APPSECRET = KHDBConfig.getParamConfig(eliteBean, opsource + "-appSecret");
            log.debug("获取到的微信公众号配置信息【APPID】：" + APPID + "【APPSECRET】：" + APPSECRET);

            // 如果未获取到对应APPID直接返回失败
            if (KHUtil.isNull(APPID) || KHUtil.isNull(APPSECRET)) {
                String err_Info = KHUtil.isNull(opsource) ? "当前入参opsource为空,请检查" : "当前来源:" + opsource + "未查询到对应APPID配置,请检查";
                log.warn("未知类型公众号嵌入警告:" + err_Info);
                return err_Info;
            }

            // 通过Code信息获取openid
            JSONObject apiTokenJson = new JSONObject();
            if (opsource == "wxc") {
                apiTokenJson = JSONObject.parseObject(Util.doHttpGet("https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + APPID + "&secret=" + APPSECRET + "&code=" + code + "&grant_type=authorization_code", "UTF-8", 5000, 0));
                log.debug("获取微信-通过Code信息获取openid调用返回：" + apiTokenJson.toString());
            } else if (opsource == "wxq") {
                apiTokenJson = JSONObject.parseObject(Util.doHttpGet(KHDBConfig.getAPIURL(eliteBean, "SYS-InnerDomain") + "groovy/GeneralService/apiGetToken?appid=WXG_DAVCO", "UTF-8", 12000, 0));
                log.debug("通过配置信息获取企微access_token调用返回：" + apiTokenJson.toString());

                String callURL = "https://qyapi.weixin.qq.com/cgi-bin/auth/getuserinfo?access_token=" + apiTokenJson.getJSONObject("value").getString("access_token") + "&code=" + code;
                log.debug("获取企微-Code信息openid调用URL：" + callURL);

                apiTokenJson = JSONObject.parseObject(Util.doHttpGet(callURL, "UTF-8", 5000, 0));
                log.debug("获取企微-Code信息openid调用返回：" + apiTokenJson.toString());
            }

            if (apiTokenJson.containsKey("openid") || apiTokenJson.containsKey("userid")) {
                String access_token = apiTokenJson.getString("access_token");
                String refresh_token = apiTokenJson.getString("refresh_token");
                String openid = apiTokenJson.getString("openid");
                String quserid = apiTokenJson.getString("userid") != null ? apiTokenJson.getString("userid") : openid;
                String scope = apiTokenJson.getString("scope");
                log.debug("获取到的微信用户信息【access_token】：" + access_token + "【refresh_token】：" + refresh_token + "【openid】：" + openid);

                // 检查当前OPENID对应的账号类型
                List selectExits = null;
                if (opsource == "wxc") {
                    selectExits = jt.queryForList("select customer_guid as userid, loginname, 'customer' as usertype, 2 as sno from customer where open_id = ? order by sno limit 1", openid);

                } else if (opsource == "wxq") {
                    selectExits = jt.queryForList("select staff_id as userid, loginname , 'staff' as usertype, 1 as sno from staff where userid = ? order by sno limit 1", quserid);

                } else {
                    log.warn("未知类型获取用户信息警告:" + opsource);
                    return opsource;
                }

                // 获取当前登录人在系统中的信息
                String userid = "";
                String usertype = "";
                if (selectExits.size() > 0) {
                    Map selectExitsm = selectExits.get(0);
                    userid = selectExitsm.get("userid");
                    usertype = selectExitsm.get("usertype");

                } else {
                    userid = openid;
                    usertype = "notype";
                }
                log.debug("获取当前登录人在系统中的信息:" + userid + "/" + usertype);

                // 获取NGS页面信息短码
                String NGSShortenLinkURL = DOMAIN + "groovy/GeneralService/apiShortenLink?dynid=" + opdynid + "&userid=" + userid + "&usertype=" + usertype + "&woid=&taskid=" + taskid + "&expand=" + expand + "&cbtype=&opsource=" + opsource;
                log.debug("获取NGS短码调用URL：" + NGSShortenLinkURL);

                JSONObject apiLinkJson = JSONObject.parseObject(Util.doHttpGet(NGSShortenLinkURL, "UTF-8", 5000, 0));
                log.debug("获取NGS短码调用返回：" + apiLinkJson.toString());

                // 解析NGS短码调用返回
                String linkURL = apiLinkJson.getString("message");
                log.debug("获取NGS页面信息短码：" + linkURL);

                response.sendRedirect(linkURL);
            } else {
                String errcode = apiTokenJson.getString("errcode");
                String errmsg = apiTokenJson.getString("errmsg");
                log.warn("打开页面异常:" + opsource + " errcode:" + errcode + " errmsg:" + errmsg);
                response.sendRedirect(DOMAIN + "ngs/404.html?ErrorTitle=" + URLEncoder.encode("页面异常", "UTF-8") + "&ErrorInfo=" + URLEncoder.encode("错误代码：" + errcode + " 描述:" + "请联系管理员查看Server日志!", "UTF-8").replaceAll("\\+", "%20"));
            }
        }

    }
}